/*
 * The MIT License 
 *
 * Copyright (c) 2010 pf-miles
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package me.wenyue.jclassview.handler;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandlerContainer;
import org.eclipse.jetty.server.handler.ResourceHandler;

/**
 * mapping requests to other handlers according to request path, aka. the target
 * parameter
 * 
 * @author pf-miles 2010-11-11 上午11:04:39
 * 
 */
@SuppressWarnings("unchecked")
public class PathMappingHandler extends AbstractHandlerContainer {
    private static final Map<String, Handler> mapping = new LinkedHashMap<String, Handler>();
    // default handler when no handler-mapping is matched
    private static final ResourceHandler defaultHandler = new ResourceHandler();
    static {
        initHandlerMappings(ViewHandler.class);

        defaultHandler.setAliases(false);
        defaultHandler.setDirectoriesListed(false);
        defaultHandler.setResourceBase("resources");
        defaultHandler.setWelcomeFiles(new String[] { "welcome.htm" });
    }

    public Handler[] getHandlers() {
        return mapping.values().toArray(new Handler[mapping.size()]);
    }

    private static void initHandlerMappings(Class<? extends Handler>... cls) {
        if (cls != null) {
            for (Class<? extends Handler> c : cls) {
                String sname = c.getSimpleName();
                try {
                    mapping.put("/" + sname.substring(0, sname.lastIndexOf("Handler")).toLowerCase(), c
                            .newInstance());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public void handle(String target, Request baseRequest, HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {
        if (mapping.containsKey(target)) {
            mapping.get(target).handle(target, baseRequest, request, response);
        } else {
            defaultHandler.handle(target, baseRequest, request, response);
        }
    }
}
